#! -*- coding: utf-8 -*-
"""
"""
from jili.core.printlog import print
import requests, json
import time
from requests_toolbelt.multipart.encoder import MultipartEncoder
import hashlib
import base64
import hmac
def gen_sign(timestamp, secret):
    # 拼接timestamp和secret
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    # 对结果进行base64处理
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign
def upload_image(png_url,app_token):
    url = "https://open.feishu.cn/open-apis/im/v1/images"
    form = {
        'image_type': 'message',
        'image': (open(png_url, 'rb'))  # 替换为实际图片路径
    }
    multi_form = MultipartEncoder(form)
    headers = {
        'Authorization': 'Bearer '+app_token,  # 替换为实际 token
        'Content-Type': multi_form.content_type
    }
    response = requests.post(url, headers=headers, data=multi_form)
    response=response.json()
    if response["code"]==0:
        return response["data"]["image_key"]
    else:
        print("error","失败",response)
        return None

class chat_fs:
    def __init__(self,key=None,url=None,app_token=None,secret=None):
        if url:
            self.url=url
        else:
            self.url  = "https://open.feishu.cn/open-apis/bot/v2/hook/"+key
        self.upload_url="https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?debug=1&key="+key+"&type=file"
        self.send_message=""
        self.app_token=app_token
        self.secret=secret
    def split_msg(self,msg,size=4096):
        s=[]
        n0=len(msg)
        b=msg.encode("utf-8")
        n1=len(b)
        if n1>size:
            m=int(n1/size)+1
            n1=0
            size=n0/m
            for i in range(1,m):
                n2=int(size*i)
                while msg[n2]!="\n":
                    n2=n2+1
                if msg[n2]=="\n":
                    s.append(msg[n1:n2])
                    n1=n2+1
            s.append(msg[n1:])
        else:
            s.append(msg)
        return s
    def send_msg(self,msg,at_name_list={}):
        """艾特全部，并发送指定信息"""

        msgs=self.split_msg(msg)
        for msg in msgs:
            # 构造消息体
            message = {
                "msg_type": "text",  # 消息类型，文本消息为 "text"
                "content": {
                    "text": msg  # 消息内容
                }
            }
            if self.secret:
                timestamp=int(time.time())
                message ["timestamp"]=timestamp
                message["sign"] = gen_sign(timestamp,self.secret)
            # 发送 POST 请求
            response = requests.post(
                url=self.url,
                headers={"Content-Type": "application/json"},
                data=json.dumps(message)
            )
            r=response.json()
            # 输出响应结果
            if response.status_code == 200:
                print("消息发送成功:", response.json())
            else:
                print("消息发送失败:", response.status_code, response.json())
        return r

    def send_image(self,image_url):
        if self.app_token:
            ikey=upload_image(image_url,self.app_token)
            if ikey   is not None:
                message = {
                    "msg_type":"image",
                    "content":{
                        "image_key": ikey
                    }
                }
                if self.secret:
                    timestamp = int(time.time())
                    message["timestamp"] = timestamp
                    message["sign"] = gen_sign(timestamp, self.secret)
                # 发送 POST 请求
                response = requests.post(
                    url=self.url,
                    headers={"Content-Type": "application/json"},
                    data=json.dumps(message)
                )
                r = response.json()
                # 输出响应结果
                if response.status_code == 200:
                    print("消息发送成功:", response.json())
                else:
                    print("消息发送失败:", response.status_code, response.json())
            return r
        else:
            print("没有app_token","不能上传")
